from odoo import models, fields, api, _
from odoo.exceptions import UserError, ValidationError


# 审批流类
class Workflow(models.Model):
    _inherit = 'sb.workflow'

    # 关联产品表
    product_id = fields.Many2one('product.template', string="Associated Product", ondelete="cascade")

    workflow_type = fields.Selection(selection_add=[
        ('product', 'Product')
    ], ondelete={'activity': 'cascade'})

    # 获取审批流状态
    @api.depends('sb_workflow_item_ids', 'sb_workflow_item_ids.state')
    def _compute_state(self):
        for workflow in self:
            w_item_states = []
            # 获取全部审批项状态
            for w_item in workflow.sb_workflow_item_ids:
                w_item_states.append(w_item.state)
            # 判断
            if 'no_pass' in w_item_states:
                workflow.state = 'fail_to_approve'
            elif 'approval' in w_item_states or 'wait_forward' in w_item_states:
                workflow.state = 'approval'
            else:
                workflow.state = 'approve'
                if workflow.workflow_type == 'product':
                    workflow.product_id.sudo().write({
                        'state': 'enable'
                    })
                    workflow.product_id.sudo().write({
                        'active': True
                    })
                    # workflow.product_id.categ_id.sudo().write({
                    #     'flow_number': workflow.product_id.categ_id.flow_number+1
                    # })
